/**
 * @description: 数据组装
 * @version: 0.0.1
 * @author: xiech
 * @Date: 2023-06-01 14:09:43
 */

import { NextFunction, Context } from '@midwayjs/koa';
import { Config, Middleware, Inject } from '@midwayjs/decorator';
import { RouterInfo, MidwayWebRouterService } from '@midwayjs/core';

@Middleware()
export class FormatMiddleware {
  @Config('middleware.format')
  formatConfig: any;

  @Inject()
  webRouterService: MidwayWebRouterService;

  @Inject()
  notFormatRouters: RouterInfo[];

  resolve() {
    return async (ctx: Context, next: NextFunction) => {
      // 执行下一个 Web 中间件，最后执行到控制器
      const result = await next();

      const routeInfo = await this.webRouterService.getMatchedRouterInfo(ctx.path, ctx.method);
      if (
        this.notFormatRouters.some(
          o =>
            o.requestMethod === routeInfo.requestMethod &&
            o.url === routeInfo.url
        )
      ) {
        return result;
      }
      
      // 数据封装
      return {
        errorCode: 0,
        errorMessage: 'ok',
        success: true,
        data: result,
      };
    };
  }

  public match(ctx: Context): boolean {
    const { path } = ctx;
    const { prefix } = this.formatConfig;
    // const exist = ignore.find((item: string) => {
    //   return item.match(path);
    // });
    return path.indexOf(prefix) === 0;
  }

  static getName(): string {
    return 'format';
  }
}
